//app.js   // "appid": "wx5fdc13171cdd72fb",

import { config } from './utils/config.js'
import { HTTP } from './utils/http.js'
import wg_util from './utils/util'

let http = new HTTP()
var QQMapWX = require('./utils/qqmap-wx-jssdk.js');
wx.wg_util = wg_util;

App({
	onLaunch: function (options) {
		if (options.scene == 1007 || options.scene == 1008) {
			this.globalData.share = true;
			wx.redirectTo({
				url: 'pages/index/index',
			})
		} else {
			this.globalData.share = false;
		}
		wx.getSystemInfo({ // 获取设备信息
			success: res => {
				this.globalData.height = res.statusBarHeight;
				this.globalData.windowHeight = res.windowHeight
				if (res.model.indexOf("iPhone X") != -1) {
					this.globalData.white = true
				}
			}
		});
		this.screenSize()
		if (wx.getStorageSync("nickName")) {
			this.updataUserinfo()
		}
		this.globalData.baseRestUrl = this.globalData.is_debug ? config.debug_url : config.api_blink_url
		if (this.globalData.is_debug == true) {
			this.globalData.tmplIds = ['qTQP0yzEevCI0va06ZP2w7OQ5Y97YcRmUcQ4EtyzRvs']
		} else {
			this.globalData.tmplIds = ['Mx_IsFd62nWxF6kLXi3RXrDINFKLqF2MKrv0m9IUhz0']
		}

	},
	hideShareMenu() {
		wx.hideShareMenu({
			success: () => {
				console.log('隐藏 成功')
			},
			complete: () => { }
		})
	},
	// 更新用户信息
	updataUserinfo() {
		wx.getUserInfo({
			success: function (res) {
				wx.setStorageSync("nickName", res.userInfo.nickName)
				wx.setStorageSync("avatarUrl", res.userInfo.avatarUrl)
			}
		})
	},
	// 清空菜单和菜篮
	updataCar() {
		wx.setStorageSync("select-menus", [])
		wx.setStorageSync("select-goods", [])
		wx.showToast({
			title: '位置发生改变，菜单和菜篮数据已重置',
			icon: "none"
		})
	},
	// 有无地址的验证
	isAddress() {
		return new Promise((resolve, reject) => {
			if (wx.getStorageSync("address")) {
				resolve(true)
			} else {
				wx.showToast({
					title: '请先确认您的地址',
					icon: "none"
				})
				resolve(false)
			}
		})
	},
	screenSize: function () {
		var that = this;
		wx.getSystemInfo({
			success: function (res) {
				var ww = res.windowWidth;
				var hh = res.windowHeight;
				that.globalData.ww = ww;
				that.globalData.hh = hh;
			}
		})
	},
	getUserLocation: function (callback) {
		let vm = this
		wx.getSetting({
			success: (res) => {
				// res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
				// res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
				// res.authSetting['scope.userLocation'] == true    表示 地理位置授权
				// 拒绝授权后再次进入重新授权
				if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
					// console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
					wx.showModal({
						title: '',
						content: '味歌需要获取你的地理位置，请确认授权',
						success: function (res) {
							if (res.cancel) {
								return false
							} else if (res.confirm) {
								wx.openSetting({
									success: function (dataAu) {
										// console.log('dataAu:success', dataAu)
										if (dataAu.authSetting["scope.userLocation"] == true) {
											//再次授权，调用wx.getLocation的API
											vm.getLocation(dataAu, callback)
										} else {
											wx.showToast({
												title: '授权失败',
												icon: 'none'
											})
										}
									}
								})
							}
						}
					})
				}
				// 初始化进入，未授权
				else if (res.authSetting['scope.userLocation'] == undefined) {
					// console.log('authSetting:status:初始化进入，未授权', res.authSetting['scope.userLocation'])
					//调用wx.getLocation的API
					vm.getLocation(res, callback)
				}
				// 已授权
				else if (res.authSetting['scope.userLocation']) {
					// console.log('authSetting:status:已授权', res.authSetting['scope.userLocation'])
					//调用wx.getLocation的API
					vm.getLocation(res, callback)
				}
			}
		})
	},
	// 微信获得经纬度
	getLocation: function (userLocation, callback) {
		let vm = this
		wx.getLocation({
			type: "wgs84",
			success: function (res) {
				// console.log('getLocation:success', res)
				var latitude = res.latitude
				var longitude = res.longitude
				callback && callback();
			},
			fail: function (res) {
				// console.log('getLocation:fail', res)
				if (res.errMsg === 'getLocation:fail:auth denied') {
					wx.showToast({
						title: '拒绝授权',
						icon: 'none'
					})
				}
				if (!userLocation || !userLocation.authSetting['scope.userLocation']) {
					vm.getUserLocation(callback)
				} else if (userLocation.authSetting['scope.userLocation']) {
					wx.showModal({
						title: '',
						content: '请在系统设置中打开定位服务',
						showCancel: false,
						success: result => {

						}
					})
				} else {
					wx.showToast({
						title: '授权失败',
						icon: 'none'
					})
				}
			}
		})
	},
	login() {
		var that = this
		let address = wx.getStorageSync("address")
		if (!address) { // 获取当前位置 
			let qqmapsdk = new QQMapWX({
				key: "OI5BZ-G3FWJ-A6VFG-FGA5U-AZHAT-2NBVY"
			});
			// 唤起获取地理位置授权
			that.getUserLocation(function () {
				wx.getLocation({
					type: 'wgs84',
					success: (res) => {
						// 获取精确的地理位置
						qqmapsdk.reverseGeocoder({
							//获取输入框值并设置keyword参数
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (res) => {//搜索成功后的回调
								console.log('===================', res.result)
								var address = {
									address: res.result.address_component.street,
									title: res.result.address_component.street,
									id: res.result.address_reference.street.id,
									addr: res.result.address,
									city: res.result.address_component.city,
									district: res.result.address_component.district,
									province: res.result.address_component.province,
									latitude: res.result.location.lat,
									longitude: res.result.location.lng,

								}
								wx.setStorageSync("address", address)
								// that.setData({
								//     address: res.result.address_component.street
								// });
								wx.setStorageSync('city_name', res.result.address_component.city)
							}
						});
					},
					fail: (err) => {
						console.log(err)
						wx.hideLoading();
					}
				})

			});
		}
	},
	// bezier: function(points, times) {
	//     console.log('points', points)
	//     console.log('times', times)
	//         // 0、以3个控制点为例，点A,B,C,AB上设置点D,BC上设置点E,DE连线上设置点F,则最终的贝塞尔曲线是点F的坐标轨迹。
	//         // 1、计算相邻控制点间距。
	//         // 2、根据完成时间,计算每次执行时D在AB方向上移动的距离，E在BC方向上移动的距离。
	//         // 3、时间每递增100ms，则D,E在指定方向上发生位移, F在DE上的位移则可通过AD/AB = DF/DE得出。
	//         // 4、根据DE的正余弦值和DE的值计算出F的坐标。
	//         // 邻控制AB点间距
	//     var bezier_points = [];
	//     var points_D = [];
	//     var points_E = [];
	//     const DIST_AB = Math.sqrt(Math.pow(points[1]['x'] - points[0]['x'], 2) + Math.pow(points[1]['y'] - points[0]['y'], 2));
	//     // 邻控制BC点间距
	//     const DIST_BC = Math.sqrt(Math.pow(points[2]['x'] - points[1]['x'], 2) + Math.pow(points[2]['y'] - points[1]['y'], 2));
	//     // D每次在AB方向上移动的距离
	//     const EACH_MOVE_AD = DIST_AB / times;
	//     // E每次在BC方向上移动的距离 
	//     const EACH_MOVE_BE = DIST_BC / times;
	//     // 点AB的正切
	//     const TAN_AB = (points[1]['y'] - points[0]['y']) / (points[1]['x'] - points[0]['x']);
	//     // 点BC的正切
	//     const TAN_BC = (points[2]['y'] - points[1]['y']) / (points[2]['x'] - points[1]['x']);
	//     // 点AB的弧度值
	//     const RADIUS_AB = Math.atan(TAN_AB);
	//     // 点BC的弧度值
	//     const RADIUS_BC = Math.atan(TAN_BC);
	//     // 每次执行
	//     for (var i = 1; i <= times; i++) {
	//         // AD的距离
	//         var dist_AD = EACH_MOVE_AD * i;
	//         // BE的距离
	//         var dist_BE = EACH_MOVE_BE * i;
	//         // D点的坐标
	//         var point_D = {};
	//         point_D['x'] = dist_AD * Math.cos(RADIUS_AB) + points[0]['x'];
	//         point_D['y'] = dist_AD * Math.sin(RADIUS_AB) + points[0]['y'];
	//         points_D.push(point_D);
	//         // E点的坐标
	//         var point_E = {};
	//         point_E['x'] = dist_BE * Math.cos(RADIUS_BC) + points[1]['x'];
	//         point_E['y'] = dist_BE * Math.sin(RADIUS_BC) + points[1]['y'];
	//         points_E.push(point_E);
	//         // 此时线段DE的正切值
	//         var tan_DE = (point_E['y'] - point_D['y']) / (point_E['x'] - point_D['x']);
	//         // tan_DE的弧度值
	//         var radius_DE = Math.atan(tan_DE);
	//         // 地市DE的间距
	//         var dist_DE = Math.sqrt(Math.pow((point_E['x'] - point_D['x']), 2) + Math.pow((point_E['y'] - point_D['y']), 2));
	//         // 此时DF的距离
	//         var dist_DF = (dist_AD / DIST_AB) * dist_DE;
	//         // 此时DF点的坐标
	//         var point_F = {};
	//         point_F['x'] = dist_DF * Math.cos(radius_DE) + point_D['x'];
	//         point_F['y'] = dist_DF * Math.sin(radius_DE) + point_D['y'];


	//         bezier_points.push(point_F);
	//     }
	//     return {
	//         'bezier_points': bezier_points
	//     };
	// },

	globalData: {
		is_debug: true, //生产为false测试为true
		baseRestUrl: null,
		is_auth: false, // 用户是否授权
		userInfo: null,
		share: false, // 分享默认为false
		height: 0,
		windowHeight: 0, // 设备的视窗高度
		white: false, // iphone X系列手机的底部兼容
		has: true, // 附近是否有商家
		globalAddress: '',
		statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],  //获取到顶部状态栏的高度
		tmplIds: []
	}
});

//味歌+  qTQP0yzEevCI0va06ZP2w7OQ5Y97YcRmUcQ4EtyzRvs
//味歌正式   Mx_IsFd62nWxF6kLXi3RXrDINFKLqF2MKrv0m9IUhz0


// var fundebug = require("./utils/fundebug.1.3.1.min.js");
// fundebug.init({
//   apikey: "9609a8429712cdca7221e232bf4968e5be3d238f1a9a068d9faf0371a90f8da0"
// });

// fundebug.test()